# Xata Chat Memory

[Xata](https://xata.io) is a serverless data platform, based on PostgreSQL. It provides a type-safe TypeScript/JavaScript SDK for interacting with your database, and a
UI for managing your data.

With the `XataChatMessageHistory` class, you can use Xata databases for longer-term persistence of chat sessions.

Because Xata works via a REST API and has a pure TypeScript SDK, you can use this with [Vercel Edge](https://vercel.com/docs/concepts/functions/edge-functions/edge-runtime), [Cloudflare Workers](https://developers.cloudflare.com/workers/) and any other Serverless environment.

## Setup

### Install the Xata CLI

```bash
npm install @xata.io/cli -g
```

### Create a database to be used as a vector store

In the [Xata UI](https://app.xata.io) create a new database. You can name it whatever you want, but for this example we'll use `langchain`.

When executed for the first time, the Xata LangChain integration will create the table used for storing the chat messages. If a table with that name already exists, it will be left untouched.

### Initialize the project

In your project, run:

```bash
xata init
```

and then choose the database you created above. This will also generate a `xata.ts` or `xata.js` file that defines the client you can use to interact with the database. See the [Xata getting started docs](https://xata.io/docs/getting-started/installation) for more details on using the Xata JavaScript/TypeScript SDK.

## Usage

import CodeBlock from "@theme/CodeBlock";

Each chat history session stored in Xata database must have a unique id.

In this example, the `getXataClient()` function is used to create a new Xata client based on the environment variables. However, we recommend using the code generated by the `xata init` command, in which case you only need to import the `getXataClient()` function from the generated `xata.ts` file.

import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx";

<IntegrationInstallTooltip></IntegrationInstallTooltip>

```bash npm2yarn
npm install @langchain/openai @langchain/community
```

import Example from "@examples/memory/xata.ts";

<CodeBlock language="typescript">{Example}</CodeBlock>

### With pre-created table

If you don't want the code to always check if the table exists, you can create the table manually in the Xata UI and pass `createTable: false` to the constructor. The table must have the following columns:

- `sessionId` of type `String`
- `type` of type `String`
- `role` of type `String`
- `content` of type `Text`
- `name` of type `String`
- `additionalKwargs` of type `Text`

import Advanced from "@examples/memory/xata-advanced.ts";

<CodeBlock language="typescript">{Advanced}</CodeBlock>
